// 实现登录和注册盒子的切换
$('#link_reg').on('click', function () {
  $('.login-box').hide()
  $('.reg-box').show()
})

$('#link_login').on('click', function () {
  $('.reg-box').hide()
  $('.login-box').show()
})

// 自定义校验规则
let form = layui.form
form.verify({
  pwd: [/^[\S]{6,12}$/, '密码必须6-12位，且不能出现空格'],
  // data是当前规则所在表单里输入的内容
  repeatpwd: function (data) {
    let pwd = $('.password').val()
    if (pwd != data) {
      return '两次密码不一致'
    }
  }
})

let layer = layui.layer
// 注册功能
$('.regform').on('submit', function (e) {
  e.preventDefault()
  let username = $('.regusername').val()
  let password = $('.password').val()
  $.ajax({
    url: '/api/reguser',
    type: 'post',
    data: {
      username,
      password
    },
    success: function (msg) {
      console.log(msg)
      if (msg.status == 0) {
        // 自动跳转到登录框登录
        $('#link_login').click()
      }
    }
  })
})

$('.loginform').on('submit', function (e) {
  e.preventDefault()
  // 获取用户和密码
  let username = $('.lusername').val()
  let password = $('.lpassword').val()
  // 发起ajax请求
  $.ajax({
    url: '/api/login',
    type: 'post',
    data: {
      username,
      password
    },
    success: function (msg) {
      console.log(msg)
      if (msg.status == 0) {
        localStorage.setItem('token', msg.token)
        // 跳转到后台首页
        location.href = "/index.html"
      } else {
        layer.msg('登录失败')
      }
    }
  })
})
